package com.dcy.daily.common.exception;

import com.dcy.daily.common.core.domain.ResultVO;
import com.dcy.daily.common.enums.ResponseCodeEnum;
import com.dcy.daily.common.utils.I18nUtil;
import com.dcy.daily.common.utils.JsonFormatUtils;
import com.dcy.daily.common.utils.StringUtils;
import com.dcy.daily.common.constant.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author duanchunyu
 * @version 1.0.0
 * @createTime 2021年11月03日 15:30
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 基础异常
     */
    @ExceptionHandler({BaseException.class,ValidateException.class})
    public ResultVO<String> baseException(BaseException e)
    {
        String msg = e.getMessage();
        StringBuilder sb = new StringBuilder();
        String[] codes = e.getCodes();
        if(StringUtils.isNotNull(codes)){
            String errCode = codes[1];
            String errorCodeMsg = I18nUtil.message(errCode, e.getArgs());
            sb.append(errCode).append(Constants.VERTICAL_LINE_SPACE);
            if(errorCodeMsg.equals(errCode)){
                sb.append(e.getErrMSg());
            }else{
                sb.append(errorCodeMsg).append(e.getErrMSg());
            }
        }else{
            sb.append(e.getCode()).append(Constants.VERTICAL_LINE_SPACE);
            if(msg.equals(e.getCode())){
                sb.append(e.getErrMSg());
            }else{
                sb.append(msg).append(e.getErrMSg());
            }
        }
        ResultVO<String> resultVO = ResultVO.error(e.getCode() ,msg);
        sb.append(" (").append(JsonFormatUtils.obj2jsonIgnoreNull(resultVO)).append(")");
        log.error(sb.toString(), e.isPrintExcep()?e:null);
        return resultVO;
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResultVO<String> handleException(Exception e)
    {
        String code = ResponseCodeEnum.EXCEPTION.getCode();
        String msg = I18nUtil.message(code);
        ResultVO<String> resultVO = ResultVO.error(Constants.MODULE.EXCEPTION + code,msg);
        StringBuilder sb = new StringBuilder();
        sb.append(Constants.MODULE.EXCEPTION).append(code)
                .append(Constants.VERTICAL_LINE_SPACE).append(msg).append(" (").append(JsonFormatUtils.obj2jsonIgnoreNull(resultVO)).append(")");
        log.error(sb.toString(), e);
        return resultVO;
    }
}
